//
//  DataPointView.swift
//  MoyoungHome
//
//  Created by 李然 on 2022/8/9.
//

import UIKit
import SnapKit


public class DataPointView: View {
    
    public var pointColors:[UIColor] = []{
        didSet{
            self.updateUI()
        }
    }
    
    public var image: UIImage? {
        
        didSet {
            imageView.image = image
            
        }
    }
    
    public var imgColor : UIColor = .clear {
        didSet{
            imageView.image = UIImage(named: "handle_sleep")?.setupImageTintColor(tintColor: imgColor)
        }
    }
    
    let bgLayer = CAGradientLayer()
    
    public override func makeUI() {
        super.makeUI()
        
        self.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in

            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()

        }
        bgImageView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.isUserInteractionEnabled = true
        
       
        bgLayer.startPoint = CGPoint(x: 1, y: 0)
        bgLayer.endPoint = CGPoint(x: 1, y: 1)
        bgLayer.drawsAsynchronously = true
        lineView.layer.insertSublayer(bgLayer, at: 0)
        
        self.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.centerX.equalToSuperview()
            make.bottom.equalTo(bgImageView.snp.top).offset(-15)
            make.width.equalTo(2)
        }
    }
    
    public override func updateUI() {
        super.updateUI()
        
        lineView.layoutIfNeeded()
        
    }
    
    private lazy var lineView: View = {
        let lineView = View()
        return lineView
    }()
    
    public lazy var bgImageView: View = {
        let bgImageView = View()
        bgImageView.backgroundColor = UIColor.init(hex: "#F7F7F7")
        return bgImageView
    }()
    
    private lazy var imageView: ImageView = {
        let imageView = ImageView()
        return imageView
    }()
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        if !self.pointColors.isEmpty {
            bgLayer.colors = self.pointColors.map{$0.cgColor}
          }
        
        if !bgLayer.frame.equalTo(lineView.bounds) {
            bgLayer.frame = lineView.bounds
        }
        
    }
}




